package com.yups.web;

import com.yups.dao.EmpDao;
import com.yups.model.Emp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/LoginAction")
public class LoginAction extends HttpServlet {
	private EmpDao empDao = new EmpDao();

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String verifyCode = (String) request.getSession().getAttribute("verifyCode");
		       if(verifyCode==null || !verifyCode.equalsIgnoreCase(request.getParameter("verifyCode"))){
           Map<String,String> errors=new HashMap<>();
           errors.put("verifyCode","验证码错误.");
           forward(request,response,"errors",errors,"login.jsp");
           return;
       }
		String mob = request.getParameter("mob");
		String password = request.getParameter("password");
		Emp emp = empDao.login(mob, password);
		if (emp == null) {
			forward(request, response, "您的用户名或密码有误.", "login.jsp");
			return;
		}
		Cookie cookie = new Cookie("mob", mob);
		cookie.setPath("/");
		if ("1".equals(request.getParameter("saveUserFlag"))) {
			cookie.setMaxAge(7 * 24 * 86400);
		} else {
			cookie.setMaxAge(0);
		}
		response.addCookie(cookie);
		request.getSession().setAttribute("loginEmp", emp);
		forward(request, response, "", "index.jsp");
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().removeAttribute("loginEmp");//只清除登录状态
		forward(request, response, "感谢使用，欢迎再来.", "login.jsp");
	}

	private void forward(HttpServletRequest request, HttpServletResponse response, String key, Object value, String url) throws ServletException, IOException {
		request.setAttribute(key, value);
		request.getRequestDispatcher(url).forward(request, response);
	}

	private void forward(HttpServletRequest request, HttpServletResponse response, String msg, String url) throws ServletException, IOException {
		request.setAttribute("msg", msg);
		request.getRequestDispatcher(url).forward(request, response);
	}
}
